import { DataSet } from 'choerodon-ui/pro';
import JSONbig from 'json-bigint';
import { typeData, deployWayData } from './constants';

const mapping: any = {
  envId: {
    name: 'envId',
    type: 'string',
    label: '环境名称',
    textField: 'name',
    valueField: 'id',
  },
  checkEnvPermissionFlag: {
    name: 'skipCheckPermission',
    type: 'boolean',
    label: '是否允许非环境人员触发此部署任务',
    defaultValue: false,
  },
  deployType: {
    textField: 'name',
    valueField: 'value',
    defaultValue: deployWayData[0].value,
    name: 'deployType',
    type: 'string',
    label: '部署方式',
    options: new DataSet({
      data: deployWayData,
    }),
  },
};

const Index = (projectId: any, useStore: any, level: any) => ({
  autoCreate: true,
  fields: Object.keys(mapping).map((key) => {
    const item = mapping[key];
    switch (key) {
      case 'envId': {
        item.disabled = level !== 'project' || window.location.href.includes('project-pipeline-template');
        item.dynamicProps = {
          required: ({ record }: any) => [typeData[0].value, typeData[1].value, 'cdDeploy'].includes(record?.get('type'))
          && level === 'project' && !window.location.href.includes('project-pipeline-template'),
        };
        item.lookupAxiosConfig = () => (projectId ? ({
          method: 'get',
          //   url: `/devops/v1/projects/${projectId}/envs/
          //   list_by_active?active=true&random=${random}`,
          url: `/devops/v1/projects/${projectId}/envs/list_by_active?active=true`,
          transformResponse: (res: any) => {
            let newRes = res;
            try {
              newRes = JSONbig.parse(res);
              useStore.setValueIdList(newRes.filter((r: any) => r.permission));
              return newRes.filter((r: any) => r.permission);
            } catch (e) {
              return newRes;
            }
          },
        }) : undefined);
        break;
      }
      case 'checkEnvPermissionFlag': {
        item.disabled = level !== 'project' || window.location.href.includes('project-pipeline-template');
        break;
      }
      case 'deployType': {
        item.disabled = level !== 'project' || window.location.href.includes('project-pipeline-template');
        break;
      }
      default: {
        break;
      }
    }
    return item;
  }),
});

export default Index;
